<?php

namespace common\models;

use Yii;
use yii\db\ActiveRecord;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use Helper;

class Signature extends ActiveRecord
{

    public static function tableName()
    {
        return '{{%sms_signature}}';
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['addtime']
                ]
            ],

        ];
    }

    public function rules()
    {
        return [
            [['name'], 'required', 'message' => Yii::t('code', '1054')],
            [['appkey'], 'required', 'message' => Yii::t('code', '1035')],
            [['name'], 'unique', 'message' => Yii::t('code', '1055')]
        ];
    }

    /**
     * 更新余额缓存
     * @param  $appkey 用户appkey
     * @return bool 返回操作结果
     */
    public static function updateSignatureCache()
    {
        $signatures = Signature::find()->orderBy('id ASC')->asArray()->all();
        if (!empty($signatures)) {
            $result = [];
            foreach ($signatures as $k => $v) {
                $result[$v['id']] = (array)$v;
            }
            $name = 'signatureCache';
            Yii::$app->redis->set($name, json_encode($result));
        }
        return true;
    }

    public static function getCache($serach = [], $setkey = false)
    {
        $result = [];
        $list = Yii::$app->redis->get('signatureCache');
        if (empty($list)) {
            $list = Signature::find()->asArray()->all();
        } else {
            $list = json_decode($list, true);
        }
        if (!empty($list)) {
            if (empty($serach)) {
                if ($setkey) {
                    foreach ($list as $k => $v) {
                        $result[$v[$setkey]] = $v;
                    }
                } else {
                    $result = $list;
                }
            } else {
                $serachKey = array_keys($serach);
                foreach ($list as $k => $v) {
                    $tflag = true;
                    foreach ($serachKey as $ks) {
                        if ($v[$ks] != (string)$serach[$ks]) {
                            $tflag = false;
                            break;
                        }
                    }
                    if ($tflag) {
                        if ($setkey) {
                            $result[$v[$setkey]] = (array)$v;
                        } else {
                            $result[] = (array)$v;
                        }
                    }
                }
            }
        }
        return $result;
    }


}


?>